package com.sunday.fangbeibei.app;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.AreaInfo;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.orm.UserInfo;

/**
 * 
 * @author 晨曦
 *
 */

public class PortalApplication extends Application implements HttpResponseInterface{

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		initImageLoader(this);
		initUserInfo();
	}
	
	private void initImageLoader(Context context) {
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
				.threadPriority(Thread.NORM_PRIORITY - 2)  //设置线程的优先级
				.denyCacheImageMultipleSizesInMemory()    //当同一个Uri获取不同大小的图片，缓存到内存时，只缓存一个。默认会缓存多个不同的大小的相同图片
				.discCacheFileNameGenerator(new Md5FileNameGenerator())   //设置文件缓存的名字  Md5FileNameGenerator()：通过Md5将url生产文件的唯一名字
				.build();
		ImageLoader.getInstance().init(config);
	}
	
	// 自动登陆
	private void initUserInfo(){
		
		SharedPreferences settings = getSharedPreferences("fbb", 0);
		String name=settings.getString("name", "");
		String pwd=settings.getString("password", "");
		
		if(!name.equals("")&&!pwd.equals("")){
			RequestParams params=new RequestParams();
			params.add("mobi", name);
			params.add("password", pwd);
			HttpTool.HttpPost(0, this, ApplicationConstants.SERVER_URL+"/mobi/account/log", params, this, new TypeToken<BaseResult<UserInfo>>() {
			}.getType());
			
		}
		
	}

	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		switch(requsetCode){
		case 0:
			BaseResult<UserInfo> result0=(BaseResult<UserInfo>) result;
			if(resultStatus){
				ApplicationCache.INSTANCE.setUserInfo(result0.getResult());

				if(result0.getResult().getType()!=3){
					AreaInfo info=new AreaInfo();
					info.setName(result0.getResult().getCityName());
					info.setParentId(result0.getResult().getDistrictId());//城市id
					ApplicationCache.INSTANCE.setAreaInfo(info);
				}
				
			}
			break;
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		
	}
	
}
